package org.to_zero.springboot.security.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.to_zero.springboot.security.entity.SysAuth;
import org.to_zero.springboot.security.entity.SysUser;
import org.to_zero.springboot.security.mapper.UserMapper;

import java.util.List;
import java.util.Objects;

@Service
public class NativeUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = new LambdaQueryChainWrapper<>(userMapper).eq(Objects.nonNull(username), SysUser::getUsername, username).one();
        if (Objects.isNull(sysUser)) throw new UsernameNotFoundException("用户名或密码错误，请重新输入！");
        List<SysAuth> sysAuths = userMapper.selectAuthListByUserId(sysUser.getId());
        sysUser.setAuthorities(sysAuths);
        return sysUser;
    }
}
